const Router = require('koa-router')
const router = new Router({
  prefix: '/api/v1/classic'
})

const { Auth } = require('../../../middlewares/auth')
const { PositiveIntegerValidator } = require('@validator')
const { Flow } = require('@root/app/models/flow')
const { Art } = require('@models/art')
const { Favor } = require('../../models/favor')

router.get('/latest', new Auth().m, async (ctx, next) => {
  // 权限 复杂
  // 限制 token 角色
  // 普通用户 管理员
  // 分级 scope
  // 8 普通用户 16 管理员

  // 排序
  const flow = await Flow.findOne({
    order: [
      ['index', 'DESC']
    ]
  })
  const art = await Art.getData(flow.art_id, flow.type)
  const likeLatest = await Favor.userLikeIt(flow.art_id, flow.type, ctx.auth.uid)
  // 序列化时，需要使用dataValues上做数据相关修改工作，但不太好
  // art.dataValues.index = flow.index
  art.setDataValue('index', flow.index)
  art.setDataValue('like_status', likeLatest)
  ctx.body = art
})

router.get('/:index/next', new Auth().m, async(ctx, next) => {
  const v = await new PositiveIntegerValidator().validate(ctx, {
    id: 'index'
  })
  const index = v.get('path.index')
  ctx.body = await getArtByIndex(index + 1, ctx.auth.uid)
})

router.get('/:index/previous', new Auth().m, async(ctx, next) => {
  const v = await new PositiveIntegerValidator().validate(ctx, {
    id: 'index'
  })
  const index = v.get('path.index')
  ctx.body = await getArtByIndex(index - 1, ctx.auth.uid)
})

async function getArtByIndex(index, uid) {
  const flow = await Flow.findOne({
    where: {
      index
    }
  })
  if (!flow) {
    throw new global.errs.NotFound()
  }
  const { art_id, type } = flow
  const art = await Art.getData(art_id, type)
  const like = await Favor.userLikeIt(art_id, type, uid)
  art.setDataValue('index', index)
  art.setDataValue('like_status', like)
  return art
}

module.exports = router